<template>
  <div class="chat-container">
    <div class="message-list">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message-item', message.sender]"
        :style="{
          backgroundColor: message.sender === 'user' ? '#f1f1f1' : '#f1f1f1',
        }"
      >
        <div class="message-wrapper">
          <!-- 用户消息反转布局 -->
          <div v-if="message.sender === 'user'" class="user-layout">
            <!-- <div class="message-right">
              <div  class="time">{{ formatTime(message.time) }}</div>
            </div> -->
            <div class="message-left">
              <div class="user-name">曹曙光</div>
              <img :src="userAvatar" class="avatar" alt="用户头像" />
            </div>
          </div>
          <!-- 机器人消息保持原布局 -->
          <div v-else class="bot-layout">
            <div class="paper-action">
              <el-tooltip
                class="item"
                effect="dark"
                content="应用于当前文件"
                placement="bottom"
              >
                <i class="el-icon-edit"></i>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="在光标出插入"
                placement="bottom"
              >
                <i class="el-icon-document-copy"></i>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="复制"
                placement="bottom"
              >
                <i class="el-icon-edit-outline"></i>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="更多"
                placement="bottom"
              >
                <i class="el-icon-s-operation"></i>
              </el-tooltip>
            </div>
            <div class="message-left">
              <img :src="botAvatar" class="avatar" alt="机器人头像" />
              <div class="user-name">智能助手</div>
            </div>
            <div class="message-right">
              <!-- <div class="time">{{ formatTime(message.time) }}</div> -->
            </div>
          </div>
        </div>
        <div class="message-content">
          <span class="message-text">
            <MarkDown :markdownContent="message.content" />
          </span>
        </div>
      </div>
    </div>

    <div class="input-area">
      <div class="tip-quest">进一步提示的问题</div>
      <div class="send-quest">
        <div class="input-location">当前文件路径</div>
        <div class="input-serch">
          <input
            v-model="newMessage"
            @keyup.enter="sendMessage"
            placeholder="输入消息..."
            class="message-input"
          />
          <el-button @click="sendMessage" class="send-btn" type="success"
            >发送</el-button
          >
        </div>
        <div class="user-comman">
          <div class="conmmon">
            <i class="el-icon-microphone"></i>
            <i class="el-icon-paperclip"></i>
            <i class="el-icon-s-opportunity"></i>
          </div>
          <div class="model">
            <el-select
              class="model-select"
              v-model="value"
              placeholder="请选择模型"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <!-- 发送调度 -->
            <i class="el-icon-s-promotion"></i>
            <!-- 结束按钮 -->
            <i class="el-icon-video-play"></i>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { fetchEventSource } from '@microsoft/fetch-event-source';
import MarkDown from './MarkDown.vue';

export default {
  components: {
    MarkDown,
  },
  data() {
    return {
      options: [
        {
          value: '1',
          label: 'DeepSeek-R1',
        },
        {
          value: '2',
          label: 'DeepSeek-V3',
        },
        {
          value: '3',
          label: 'qwen-vl-max',
        },
      ],
      value: '',
      externalMarkdownData: '',
      newMessage: '',
      messages: [],
      welcomeSent: false,
      userAvatar:
        'https://fastly.picsum.photos/id/290/800/600.jpg?hmac=eyZn0rkb9U57eIoyGu-dw_Hq4-cVMxstLsK2RO-2jxs',
      botAvatar: 'https://i.pravatar.cc/40?img=33',
    };
  },
  mounted() {
    this.sendWelcomeMessage();
    window.addEventListener('message', (event) => {
      if (event.data.type === 'newMessages') {
        const lastMessage = this.messages[this.messages.length - 1];
        if (
          lastMessage?.sender === 'bot' &&
          lastMessage.content === '正在等待回复...'
        ) {
          // 替换等待提示为实际内容
          this.messages.splice(this.messages.length - 1, 1, {
            sender: 'bot',
            content: event.data.data.content,
            time: new Date(),
          });
        } else {
          this.addMessage('bot', event.data.data.content);
        }
      }
    });
  },
  methods: {
    // 发送测试请求
    async sendTestService(data) {
      // let flag = false;

      try {
        fetchEventSource('https://api.deepseek.com/chat/completions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: 'Bearer sk-de11e7d34ff2413c9228e583a937865b',
          },
          body: JSON.stringify({
            model: 'deepseek-chat',
            messages: [{ role: 'system', content: data }],
            stream: true,
            files: '',
          }),
          async onopen(response) {
            console.log(':::response ', response);
          },
          onmessage: (msg) => {
            // 检查是否已经有一个未完成的 bot 消息
            const lastMessage = this.messages[this.messages.length - 1];
            if (!lastMessage || lastMessage.sender !== 'bot') {
              // 如果没有未完成的 bot 消息，则添加一个新的消息框
              this.addMessage('bot', '');
            }

            // 遍历消息内容并追加到最后一个消息框
            for (const key in msg) {
              if (Object.prototype.hasOwnProperty.call(msg, key)) {
                const element = msg['data'];
                try {
                  const data = JSON.parse(element).choices[0].delta.content;
                  if (data) {
                    const lastContent =
                      this.messages[this.messages.length - 1].content;
                    // 检查新内容是否已经存在，避免重复追加
                    if (!lastContent.endsWith(data)) {
                      this.messages[this.messages.length - 1].content += data;
                      this.externalMarkdownData += data;
                    }
                  }
                } catch (error) {
                  console.error('消息解析失败:', error);
                }
              }
            }
          },
          // 停止按钮
          onclose() {
            console.log('Connection closed');
          },
          onerror(err) {
            console.error('Error:', err);
          },
        });
      } catch (err) {
        console.error('Error:', err);
      }
    },
    //! 发送消息到父窗口
    sendMessageToWebview(message) {
      console.log('message::: ', message);
      // window.parent.postMessage(
      //   {
      //     type: 'iframeMessage',
      //     data: message,
      //   },
      //   '*'
      // );

      // 本地查询
      this.sendTestService(this.newMessage);
    },
    sendMessage() {
      if (!this.newMessage.trim()) return;
      const userInfo = {
        userName: '曹曙光',
        userId: '001',
        userAvatar:
          'https://fastly.picsum.photos/id/290/800/600.jpg?hmac=eyZn0rkb9U57eIoyGu-dw_Hq4-cVMxstLsK2RO-2jxs',
        message: this.newMessage,
        time: new Date(),
      };

      this.sendMessageToWebview(JSON.stringify(userInfo));

      this.addMessage('user', this.newMessage);
      this.newMessage = '';
    },
    sendWelcomeMessage() {
      this.addMessage('bot', '欢迎使用智能聊天机器人！');
    },
    addMessage(sender, content) {
      console.log('sender---->', sender);
      this.messages.push({
        sender,
        content,
        time: new Date(),
      });
    },
    formatTime(time) {
      return time.toLocaleTimeString().replace(/:\d+ /, ' ');
    },
  },
};
</script>

<style scoped>
.message-item {
  flex-direction: column !important; /* 保持原有垂直排列 */
  max-width: 90%; /* 适当放宽消息宽度 */
}

/* 用户消息布局反转 */
.user-layout {
  display: flex;
  justify-content: flex-end;
}
.bot-layout {
  width: 100%;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-left,
.message-right {
  display: flex;
  align-items: center;
}

.message-left {
  margin-right: 16px;
}

.message-right {
  margin-left: 16px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.message-wrapper {
  padding: 0px 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.message-left {
  display: flex;
  align-items: center;
}

.message-content {
  background-color: inherit;
  padding: 12px 12px;
  border-radius: 18px;
  position: relative;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-item.user .avatar {
  margin-right: 0;
  margin-left: 10px;
}

.message-item.user .message-content {
  margin-left: 10px;
}

.message-item.bot .message-content {
  margin-right: 10px;
}

.chat-container {
  width: 100%;
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border-radius: 10px;
  background: #f5f5f5;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.message-list {
  border-radius: 8px;
  padding: 15px;
  background: white;
  min-height: 400px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.message-item {
  padding: 12px 12px;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  position: relative;
}

.paper-action {
  position: absolute;
  top: 2px;
  right: 10px;
  width: 120px;
  height: 20px;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  cursor: pointer;
}
.message-item.user {
  align-self: flex-end;
}

.message-item.bot {
  align-self: flex-start;
}

.message-text {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}

.timestamp {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.input-area {
  display: flex;
  flex-direction: column;
  width: 100%;
  gap: 10px;
  margin-top: 20px;
  display: flex;
}
.send-quest {
  display: flex;
  flex-direction: column;
  background-color: #d0cccc9e;
  border-radius: 12px;
  padding: 0px 12px;
}
.input-serch {
  display: flex;
  justify-content: space-between;
}
.input-location {
  text-align: left;
  color: white;
}
.user-comman {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
}
.model-select {
  width: 120px;
  height: auto;
  height: 20px;
  outline: none;
}
>>> .el-input__inner {
  height: 20px;
  color: white;
  background-color: transparent;
}

>>> .el-input__icon {
  color: white;
  height: auto;
  line-height: 20px;
}

/* 修改 el-select 的 placeholder 文本颜色 */
>>> .el-select .el-input__inner::placeholder {
  color: white;
}
/* 去掉 el-select 选中时的边框 */
>>> .el-select .el-input.is-focus .el-input__inner {
  border-color: transparent;
  box-shadow: none;
}
>>> .el-select .el-input .el-select__caret {
  color: white;
}

.tip-quest {
  text-align: left;
}

.message-input {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
}

.send-btn {
  padding: 12px 20px;
  color: white;
  border: none;
  margin: 0px 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.3s;
}

.send-btn:hover {
  background: #45a049;
}

/* 消息气泡动画 */
.message-item {
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
